package com.rui1024.servlet;

import com.rui1024.dao.UserDao;
import com.rui1024.dao.impl.UserDaoImpl;
import com.rui1024.pojo.User;
import com.rui1024.util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

public class LoginServlet extends HttpServlet {

    JDBCUtil jdbcUtil = new JDBCUtil();
    UserDao userDao=new UserDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        HttpSession session = req.getSession();

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String remember = req.getParameter("remember");

        System.out.println(username);
        System.out.println(password);

        Connection con=null;
        try {
            con= jdbcUtil.getCon();

            User user = new User(username, password);
            User currentUser = userDao.login(con, user);

            if(currentUser==null){
                req.setAttribute("user",user);
                req.setAttribute("errorMsg","用户名或密码错误！");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }else{
                if("remember-me".equals(remember)){
                    Cookie cookie = new Cookie("userCookie", username + "-" + password);
                    cookie.setMaxAge(1*60*60*24*7);
                    resp.addCookie(cookie);
                }
                session.setAttribute("currentUser",currentUser);
                resp.sendRedirect("main");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                jdbcUtil.closeCon(con);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
